package com.yonyou.crm.sys.dynamic.appctrl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.yonyou.crm.common.login.context.LoginContextConstant;
import com.yonyou.crm.common.rest.util.RequestUtil;
import com.yonyou.crm.common.rest.util.ResponseUtil;
import com.yonyou.crm.sys.dynamic.entity.DynamicVO;
import com.yonyou.crm.sys.dynamic.rmitf.IDynamicRmService;
import com.yonyou.iuap.context.InvocationInfoProxy;

@RestController
@RequestMapping(value = "/{version}/mbpub/dynamics")
public class AppDynamicCtrl {

	@Autowired
	private IDynamicRmService service;
	
	@RequestMapping(method = RequestMethod.GET)
	public Object getDynamicList(@PathVariable("version") String version,
			HttpServletRequest request, HttpServletResponse response){
		JSONObject paramObj = RequestUtil.getParamObject(request);
		Long userId = Long.parseLong(InvocationInfoProxy.getParameter(LoginContextConstant.UserId));
		Long roleId = Long.parseLong(InvocationInfoProxy.getParameter(LoginContextConstant.RoleId));
		int pageIndex = paramObj.getInt("page");
		int pageSize = paramObj.getInt("pageSize");
		//TODO 预留搜索条件和列表数据分类条件
//		String condition = paramObj.getString("condition");
//		String option = paramObj.getString("option");
		
		DynamicVO[] vos = service.getDynamic(userId, roleId, pageIndex, pageSize);
		return ResponseUtil.getObject(transDymList2Json(vos));
	}
	
	/**
	 * 将返回结果转化为移动端所需数据
	 * @param vos
	 * @return
	 */
	private JSONObject transDymList2Json(DynamicVO[] vos){
		JSONObject result = new JSONObject();
		if(vos == null || vos.length == 0) return result;
		List<Map<String, Object>> dynamiclist = new ArrayList<Map<String,Object>>();
		for(DynamicVO vo : vos){
			Map<String, Object> voMap = new HashMap<String, Object>();
			voMap.put("id", vo.getId());
			voMap.put("type", vo.getType());
			voMap.put("time", vo.getFormatTime());
			voMap.put("name", vo.getOwnerName());
			voMap.put("userid", vo.getOwnerId());
			voMap.put("content", vo.getContent());
			dynamiclist.add(voMap);
		}
		result.put("dynamiclist", dynamiclist);
		return result;
	}
	
	@RequestMapping(value = "userdym/{userId}",method = RequestMethod.GET)
	public Object getOwnerDynamicList(@PathVariable("version") String version,@PathVariable("userId") Long userId,
			HttpServletRequest request, HttpServletResponse response){
		DynamicVO[] vos = service.getMyDynamic(userId);
		return ResponseUtil.getObject(transDymList2Json(vos));
	}
}
